package com.sh.rabbitmq.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class MyCallback implements RabbitTemplate.ConfirmCallback,RabbitTemplate.ReturnsCallback {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack){
            log.info("确认成功：消息ID{},消息原因{}",correlationData.getId(),cause);
        }else{
            log.info("确认失败：消息ID{},消息原因{}",correlationData.getId(),cause);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.info("回退：消息内容{},交换机{}",new String(returned.getMessage().getBody()),returned.getExchange());

    }
}
